import os
# import pytesseract  # 已弃用
from paddleocr import PaddleOCR
from PIL import Image
import shutil
from multiprocessing import Pool, cpu_count
from tqdm import tqdm
import time
import cv2
import numpy as np
from concurrent.futures import ThreadPoolExecutor
import threading
import logging
import multiprocessing

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('ocr_process.log', encoding='utf-8'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

# 定义关键词和对应的文件夹名称
KEYWORDS = {
    "运输途中": ["运输途中", "运验途中", "物流途中", "配送途中","运蛆途中","运辆途","运益途中","途中"],  # 添加可能的变体
    "收到信息": ["收到信息", "已收到信息", "信息已收到",'notified','notified'],
    "拖动下方滑块完成拼图": ["拖动下方滑块完成拼图", "拖动滑块", "完成拼图"],
    "查询不到": ["查询不到", "无法查询", "未查询到","查间不到","坦和不到",'请稍后查询',"于运输商网络"],
    "成功签收": ["成功签收", "签收成功"],
    "派送异常": ["派送异常", "配送异常", "投递异常"],
    "包裹异常": ["包裹异常", "包裹损坏", "包裹破损"],
    "查询中": ["查询中", "正在查询", "查询进行中","查间中"],
}

def safe_move_file(src, dst):
    """线程安全的文件移动"""
    try:
        # 确保目标目录存在
        os.makedirs(os.path.dirname(dst), exist_ok=True)
        
        # 如果目标文件已存在，先删除
        if os.path.exists(dst):
            os.remove(dst)
            
        # 直接使用rename，这比copy+delete更快
        os.rename(src, dst)
        return True
    except Exception as e:
        logger.error(f"移动文件 {src} 时发生错误: {str(e)}")
        return False

def check_keyword_match(text, keyword_variants):
    """检查文本是否包含关键词或其变体（去除空格后再匹配）"""
    text_no_space = text.replace(' ', '').replace('\u3000', '')  # 去除半角和全角空格
    for variant in keyword_variants:
        variant_no_space = variant.replace(' ', '').replace('\u3000', '')
        if variant_no_space in text_no_space:
            return True, variant
    return False, None

